﻿using System;
using System.Globalization;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using System.Xml.XPath;

namespace RedisMonitor
{
    public static class BingImage
    {
        public static readonly DependencyProperty UseBingImageProperty = DependencyProperty.RegisterAttached("UseBingImage", typeof(object), typeof(BingImage), new PropertyMetadata(OnUseBingImageChanged));

        private static BitmapImage cachedBingImage;
        private static string imageUrl;

        private static void OnUseBingImageChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            var newValue = bool.Parse(e.NewValue.ToString());
            var image = o as Image;
            var imageBrush = o as ImageBrush;

            if (!newValue || (image == null && imageBrush == null))
            {
                return;
            }
            var context = TaskScheduler.FromCurrentSynchronizationContext();

            Task.Factory.StartNew(() =>
            {
                if (imageUrl == null)
                {

                    var client = new HttpClient();
                    var result = client.GetAsync("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=0&n=2&mbl=1&mkt=en-ww");

                    var taskStream = result.Result.Content.ReadAsStreamAsync();

                    using (taskStream.Result)
                    {
                        var doc = XDocument.Load(taskStream.Result);

                        var url = (string)doc.XPathSelectElement("/images/image/url");


                        imageUrl = string.Format(CultureInfo.InvariantCulture, "http://bing.com{0}", url);

                    }

                }

                if (imageUrl != null)
                {
                    var uri = new Uri(imageUrl, UriKind.Absolute);

                    var token = Task.Factory.CancellationToken;
                    Task.Factory.StartNew(() =>
                    {
                        cachedBingImage = new BitmapImage(uri);
                        if (image != null)
                        {
                            image.Source = cachedBingImage;
                        }
                        else if (imageBrush != null)
                        {
                            imageBrush.ImageSource = cachedBingImage;
                        }
                    }, token, TaskCreationOptions.None, context);
                }
            });
        }

        private static void SetBingImage(ImageBrush imageBrush, Image image)
        {
            var client = new HttpClient();
            var result = client.GetAsync("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=0&n=2&mbl=1&mkt=en-ww");

            result.ContinueWith(t =>
            {
                t.Result.Content.ReadAsStreamAsync().ContinueWith(o =>
                {
                    using (o.Result)
                    {
                        var doc = XDocument.Load(o.Result);

                        var url = (string)doc.XPathSelectElement("/images/image/url");

                        var uri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://bing.com{0}", url), UriKind.Absolute);

                        cachedBingImage = new BitmapImage(uri);

                        if (cachedBingImage != null)
                        {
                            if (image != null)
                            {
                                image.Source = cachedBingImage;
                            }
                            else if (imageBrush != null)
                            {
                                imageBrush.Dispatcher.Invoke((Action)(() =>
                                {
                                    imageBrush.ImageSource = cachedBingImage;
                                }));
                            }
                        }
                    }
                });
            });
        }

        private static Uri GetCurrentBingImageUrl()
        {
            var client = new HttpClient();
            var result = client.GetAsync("http://www.bing.com/hpimagearchive.aspx?format=xml&idx=0&n=2&mbl=1&mkt=en-ww");

            result.ContinueWith(task =>
            {
                task.Result.Content.ReadAsStreamAsync().ContinueWith(t =>
                {
                    using (t.Result)
                    {
                        var doc = XDocument.Load(t.Result);

                        var url = (string)doc.XPathSelectElement("/images/image/url");

                        return new Uri(string.Format(CultureInfo.InvariantCulture, "http://bing.com{0}", url), UriKind.Absolute);
                    }

                });
            });
            return null;
        }


        public static object GetUseBingImage(UIElement element)
        {
            return (object)element.GetValue(UseBingImageProperty);
        }

        public static void SetUseBingImage(UIElement element, object value)
        {
            element.SetValue(UseBingImageProperty, value);
        }
    }
}
